/**
 * 开源版本请务必保留此注释头信息，若删除捷码开源〔GEMOS〕官方保留所有法律责任追究！
 * 本软件受国家版权局知识产权以及国家计算机软件著作权保护（登记号：2018SR503328）
 * 不得恶意分享产品源代码、二次转售等，违者必究。
 * Copyright (c) 2020 gemframework all rights reserved.
 * http://www.gemframework.com
 * 版权所有，侵权必究！
 */
package com.gemframework.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gemframework.common.exception.GemException;
import com.gemframework.common.utils.GemRedisUtils;
import com.gemframework.mapper.DictionaryMapper;
import com.gemframework.model.common.DictionaryMap;
import com.gemframework.model.entity.po.Datasource;
import com.gemframework.model.entity.po.Dictionary;
import com.gemframework.model.entity.vo.DictionaryVo;
import com.gemframework.model.enums.DictionaryType;
import com.gemframework.model.enums.ExceptionCode;
import com.gemframework.service.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title: DictionaryServiceImpl
 * @Date: 2020-04-16 23:39:03
 * @Version: v1.0
 * @Description: 字典表
 * @Author: gem
 * @Email: gemframe@163.com
 * @Copyright: Copyright (c) 2020 wanyong
 * @Company: www.gemframework.com
 */
@Slf4j
@Service
@Transactional
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements DictionaryService {

    @Autowired
    GemRedisUtils redisUtils;

    @Autowired
    DictionaryMapper dictionaryMapper;

    @Override
    @Transactional
    public boolean save(Dictionary entity) {
        if(exits(entity)){
            throw new GemException(ExceptionCode.DICTIONARY_EXIST);
        }
        dictionaryMapper.insert(entity);
        //更新redis
        redisUtils.set(entity.getKeyName(),entity);
        return true;
    }

    @Override
    @Transactional
    public boolean update(Dictionary entity) {
        if(exits(entity)){
            throw new GemException(ExceptionCode.DICTIONARY_EXIST);
        }
        if(!this.updateById(entity)){
            throw new GemException(ExceptionCode.SAVE_OR_UPDATE_FAIL);
        }
        //更新redis
        redisUtils.set(entity.getKeyName(),entity);
        return true;
    }

    @Override
    @Transactional
    public boolean delete(Long id, String ids) {
        if(id!=null) {
            //删除redis
            Dictionary dictionary = getById(id);
            redisUtils.delete(dictionary.getKeyName());
            this.removeById(id);
        }
        if(StringUtils.isNotBlank(ids)){
            List<Long> listIds = Arrays.asList(ids.split(",")).stream().map(s ->Long.parseLong(s.trim())).collect(Collectors.toList());
            //批量删除redis
            List<Dictionary> dictionaries = listByIds(listIds);
            if(dictionaries!=null && !dictionaries.isEmpty()){
                for(Dictionary dictionary:dictionaries){
                    redisUtils.delete(dictionary.getKeyName());
                }
            }

            if(listIds!=null && !listIds.isEmpty()){
                this.removeByIds(listIds);
            }
        }

        return true;
    }

    @Override
    public Dictionary getByKey(String key) {
        //先查redis，缓存不存在则查DB
        Dictionary dictionary = (Dictionary) redisUtils.get(key);
        if(dictionary == null){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("key_name",key);
            dictionary = getOne(queryWrapper);
            if(dictionary != null){
                redisUtils.set(key,dictionary);
                return dictionary;
            }
        }else{
            return dictionary;
        }
        return null;
    }

    @Override
    public String getCfgByKey(String key) {
        //先查redis，缓存不存在则查DB
        Dictionary dictionary = (Dictionary) redisUtils.get(key);
        if(dictionary == null){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("key_name",key);
            queryWrapper.eq("type", DictionaryType.CONFIG.getCode());
            dictionary = getOne(queryWrapper);
            if(dictionary != null){
                redisUtils.set(key,dictionary);
                return dictionary.getValueStr();
            }
        }else{
            return dictionary.getValueStr();
        }
        return null;
    }


    @Override
    public List<DictionaryMap> getMapsByKey(String key) {
        //先查redis，缓存不存在则查DB
        Dictionary dictionary = (Dictionary) redisUtils.get(key);
        if(dictionary==null){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("key_name",key);
            queryWrapper.eq("type", DictionaryType.OPTIONS.getCode());
            dictionary = getOne(queryWrapper);
            if(dictionary != null){
                redisUtils.set(key,dictionary);
                List<DictionaryMap> list = JSONArray.parseArray(dictionary.getValueStr(), DictionaryMap.class);
                return list;
            }
        }else{
            List<DictionaryMap> list = JSONArray.parseArray(dictionary.getValueStr(), DictionaryMap.class);
            return list;
        }
        return null;
    }

    @Override
    public String getMapValue(String dictionaryKey,String mapKey) {
        //先查redis，缓存不存在则查DB
        Dictionary dictionary = (Dictionary) redisUtils.get(dictionaryKey);
        if(dictionary==null){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("key_name",dictionaryKey);
            queryWrapper.eq("type", DictionaryType.OPTIONS.getCode());
            dictionary = getOne(queryWrapper);
            if(dictionary != null){
                List<DictionaryMap> list = JSONArray.parseArray(dictionary.getValueStr(), DictionaryMap.class);
                for(DictionaryMap map:list){
                    if(map.getMapKey().equals(mapKey)){
                        return map.getMapVal();
                    }
                }
            }
        }else{
            List<DictionaryMap> list = JSONArray.parseArray(dictionary.getValueStr(), DictionaryMap.class);
            for(DictionaryMap map:list){
                if(map.getMapKey().equals(mapKey)){
                    return map.getMapVal();
                }
            }
        }
        return null;
    }

    @Override
    public boolean exits(Dictionary entity) {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper();
        queryWrapper.and(wrapper -> wrapper
                .eq("key_name",entity.getName()));
        //编辑
        if(entity.getId() != null && entity.getId() !=0){
            queryWrapper.ne("id",entity.getId());
        }
        if(count(queryWrapper)>0){
            return true;
        }
        return false;
    }
}